package com.qianfeng.day30.controller;

import com.qianfeng.day30.util.Constants;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;

@Controller
public class FileController {
    @RequestMapping("/show/{name}")
    public void show(HttpServletResponse response,
                     @PathVariable("name") String name){
        // 设置下载的响应头信息
//		response.setHeader("Content-Disposition", "attachment;fileName="+"1.jpg");
        File file = new File(Constants.IMAGE_BASE_PATH + name);
        if(file!= null && file.exists()){
            byte [] buffer = new byte[1024];
            InputStream io = null;
            OutputStream os = null;
            try {
                os = response.getOutputStream();
                io = new FileInputStream(file);
                while(io.read(buffer) != -1){
                    os.write(buffer);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }finally{
                try {
                    if(io != null){
                        io.close();
                    }
                    os.flush();
                    os.close();
                } catch (Exception e2) {
                    e2.printStackTrace();
                }
            }
        }
    }
}
